//
//  HJHomeTableViewController.swift
//  WeiBo
//
//  Created by 韩俊 on 15/12/5.
//  Copyright © 2015年 HanJun. All rights reserved.
//

import UIKit
import SVProgressHUD

private let HJStatusCellIdentifier = "CELL"

class HJHomeTableViewController: HJBasicTableViewController {

    
    var statusListViewModel: HJStatusListViewModel = HJStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !userLogin {
            
            visitorView?.setVisitorInfo(nil, message: nil)
            //        let visiV = HJVisitorView()
            //        visiV.setVisitorInfo(nil, message: nil)
            //        view = visiV
           
            return 
        }

        setupUI()
        
        loadData()
        
        tableView.dataSource = self
      
    }

    private func setupUI(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imgName: "navigationbar_friendsearch", target: self, action: "friendsearch")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imgName: "navigationbar_pop", target: self, action: "friendsearch")
        setupTableView()
    }
    
    private func setupTableView() {
        tableView.registerClass(HJStatusTableViewCell.self, forCellReuseIdentifier: HJStatusCellIdentifier)
        
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200
        tableView.separatorStyle = .None
        tableView.tableFooterView = pullUpView
        
        //let refreshControl = HJRefreshControl()
        hjRefreshControl.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        tableView.addSubview(hjRefreshControl)
    }
    
    
    func text(refreshControl:HJRefreshControl) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(5 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
            printLog("结束加载")
            refreshControl.endRefreshing()
        })
    }
    
    
    @objc private func friendsearch(){
        
        let vc = HJTempViewController()
        
        navigationController?.pushViewController(vc, animated: true)
        
    }
    
    // MARK: - 懒加载
    private lazy var pullUpView: UIActivityIndicatorView = {
        
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = UIColor.redColor()
        //view.startAnimating()
        view.sizeToFit()
        return view
    }()
    
    private var hjRefreshControl: HJRefreshControl = HJRefreshControl()
    
    private lazy var pullDownTipLabel: UILabel = {
        
        let label = UILabel()
        label.backgroundColor = UIColor.orangeColor()
        label.textColor = UIColor.whiteColor()
        label.font = UIFont.systemFontOfSize(12)
        label.textAlignment = .Center
        
//        label.hidden = true
//        
        var frame = label.frame
        frame.size = CGSizeMake(SCREENW,35)
        frame.origin.y = 64-35
        label.frame = frame
        
        return label
    }()
}


// MARK: - 加载数据
extension HJHomeTableViewController {
    
    @objc private func loadData() {
        statusListViewModel.loadData(pullUpView.isAnimating()) { (isSuccess,count) -> () in
            
            self.endLoad()
            if isSuccess {
                self.tableView.reloadData()
                if !self.pullUpView.isAnimating(){
                    self.showPullDownTips(count)
                }
                
            }else{
                SVProgressHUD.showErrorWithStatus("请求失败")
            }
        }
    }
    
    private func endLoad(){
        pullUpView.stopAnimating()
        hjRefreshControl.endRefreshing()
    }
    
    //显示下拉刷新的提示
    private func showPullDownTips(count: Int) {
        
        if self.pullDownTipLabel.hidden == false {
            return
        }
        
        if self.pullDownTipLabel.superview == nil {
            
            if let navCtrl = self.navigationController {
                navCtrl.view.insertSubview(self.pullDownTipLabel, belowSubview: navCtrl.navigationBar)
            }
        }
        
        if count == 0 {
            
            self.pullDownTipLabel.text = "没有微博数据"
        }else{
            self.pullDownTipLabel.text = "加载了\(count)条数据"
        }
        
        pullDownTipLabel.hidden = false
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.pullDownTipLabel.transform = CGAffineTransformMakeTranslation(0, self.pullDownTipLabel.frame.height)
            }) { (_) -> Void in
                UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                    self.pullDownTipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.pullDownTipLabel.hidden = true
                })
        }
    }
    
}

// MARK: - UITableViewDataSource UITableViewDelegate

extension HJHomeTableViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
       
        return statusListViewModel.statues?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier(HJStatusCellIdentifier, forIndexPath: indexPath) as! HJStatusTableViewCell
       
        cell.statusViewModel = statusListViewModel.statues![indexPath.row]
        return cell
    }
    
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        
        if !pullUpView.isAnimating() && indexPath.row == statusListViewModel.statues!.count - 1 {
            
            pullUpView.startAnimating()
            loadData()
        }
    
    }
    
    

    
}
